package thin4ca

class EntityDefResolver {

  var definitions = List[(String, DefContext)]();
  
  def addDefinition(definition: String, ctx: DefContext) = { 
    // che schifo!!
    definitions = definitions ::: List((definition, ctx));
  }
  
  def processDefinition(entities: List[EntityDef], definition: (String, DefContext)): List[EntityDef] = {
    
    val ctx = definition._2 
    val tokens = definition._1.split("\\.")
    val tokensList = definition._1.split("\\.").toList
    
    val entityNames = tokens.slice(0, tokens.length-1).toList
    var newEntities = entities;
    var prevEntity:EntityDef = null;
    if (ctx != null)
      prevEntity = 
        
    entityNames.foreach(t => {
      entities.find(t equals _.name) match {
        case Some(e) => {
          if (prevEntity != null) {
            e.addRelationTo(prevEntity)
          }
          else { 
            if (ctx != null)
              e.addRelationTo(prevEntity)
          }
          prevEntity = e;
        }
        case None => {
          val e = new EntityDef(t)
          if (prevEntity != null) {
            e.addRelationTo(prevEntity)
          }
          newEntities = e :: newEntities
          prevEntity = e;
        }
      } 
    })

    val lastEntityName = tokens(tokens.length-2)
    newEntities.find(lastEntityName equals _.name) match {
      case Some(e) => e.attributes.add(tokens(tokens.length-1))
    }
    newEntities
  }

  def resolveEntities: List[EntityDef] = {
    (List[EntityDef]() /: definitions)(processDefinition)
  }
}
